
/***
 * 
 * Executable to threshold 8-bit grayscale binary image files.
 * Usage: threshold inputfeil outputfile threshold
 * threshold should be between 1 and 254.
 * bytes under threshold will become 0, others will become 255.
 *
 ***/

#include <fstream>
#include <iostream>

using namespace std;


int main ( int argc, char **argv )
{
  // process command line args
  if ( argc != 4 )
  {
    cout << "Usage: " << argv[ 0 ] << " input output threshold" << endl;
    return -1;
  }
  char *input_file = argv[ 1 ];
  char *output_file = argv[ 2 ];
  int T = atoi ( argv[ 3 ] );
  
  ifstream input;
  cerr << "input: " << input_file << endl;
  input.open ( input_file, ios::binary );
  input.seekg ( 0, ios::end );
  int length = (int)input.tellg();
  cerr << "length = " << length << endl;
  length /= ( 512 * 512 );
  cerr << "N = " << length << endl;
  
  int buffer_size = 512 * 512;
  char *data = new char [ buffer_size ];
  
  ofstream output;
  output.open ( output_file, ios::binary );
  
  cerr << "thresholding frames:" << endl;
  input.seekg ( 0, ios::beg );
  for ( int f = 0; f < length; ++ f )
  {
    cerr << f << " ";
    input.read ( data, buffer_size );
    for ( int i = 0; i < buffer_size; ++ i )
    {
      unsigned char v = (unsigned char)data[ i ];
      if ( v < T ) data[ i ] = 0;
      else data[ i ] = 255;
    }
    output.write( data, buffer_size );
  }
  cerr << endl;
  
  input.close();
  output.close();
  delete[] data;
  return 0;
}
